package com.wlyy.bcwlw.common.aspect;

import java.lang.reflect.Method;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wlyy.bcwlw.common.annotation.SysLog;
import com.wlyy.bcwlw.common.exception.AuthenticationFailedException;
import com.wlyy.bcwlw.sys.SecurityFacade;
import com.wlyy.bcwlw.sys.operationlog.entity.UserOperationLogDTO;
import com.wlyy.bcwlw.sys.operationlog.service.UserOperationLogService;

/**
 * 
 * @ClassName. LogAspect
 * @Description. 系统日志aop
 * @author zhangyang
 * @date 2016年5月26日 下午4:45:02
 * @version V1.0
 */
@Component
@Aspect
public class LogAspect {
	
	private static final Logger logger = LogManager.getLogger(LogAspect.class);
	
	@Autowired
	private UserOperationLogService userOperationLogService;
	
	// Controller层切点
	@Pointcut("@annotation(com.wlyy.bcwlw.common.annotation.SysLog)")
	public void sysLogAspect() {
	}

	
	/**
	 * 
	* @Title. doBeforeLog
	* @Description. 前置记录日志
	* @param jpt void
	* @exception.
	 */
	@Before("sysLogAspect()")
	public void doBeforeLog(JoinPoint jpt){
		String userId = null;
		String userIp = null;
		try{
			userId = SecurityFacade.getCurUserId();
			userIp = SecurityFacade.getUserIp();
		}catch(AuthenticationFailedException e){
			logger.error(e);
			return ;
		}
	
		
		UserOperationLogDTO logDTO = new  UserOperationLogDTO();
		logDTO.setDescription(getDescription(jpt));
		logDTO.setUserId(userId);
		logDTO.setUserIp(userIp);
		userOperationLogService.insert(logDTO);
	}
	
	
	
	/**
	 * 
	* @Title. getDescription
	* @Description. 获取注解里的描述说明
	* @param jpt
	* @param type
	* @return String
	* @exception.
	 */
	private String getDescription(JoinPoint jpt){
        String methodName = jpt.getSignature().getName();    
        Object[] arguments = jpt.getArgs();    
        Class<?> targetClass = jpt.getTarget().getClass();    
        Method[] methods = targetClass.getMethods();    
        String description = "";    
         for (Method method : methods) {    
             if (method.getName().equals(methodName)) {    
                Class<?>[] clazzs = method.getParameterTypes();    
                 if (clazzs.length == arguments.length) {
                		description = method.getAnnotation(SysLog. class).description();    
                     break;    
                }    
            }    
        }    
        return description;    
	}
}
